package command

import (
	"errors"
	"fmt"
	"github.com/gookit/color"
	"github.com/gorilla/websocket"
	"github.com/spf13/cobra"
)

func MessageCommand() *cobra.Command {
	command := &cobra.Command{
		Use:   "message",
		Short: "消息服务",
		Long: "消息服务",
		Example: "订阅消息：geekros message sub\n发送消息：geekros message pub [message]",
		Args: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New(color.Red.Text("请选择操作类型 [pub|sub]"))
			}
			return nil
		},
		Run: func(cmd *cobra.Command, args []string) {
			client, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:8181", nil)
			if err != nil {
				fmt.Println(color.Red.Text("GeekROS服务连接失败，请检查GeekROS服务是否运行正常"))
				return
			}else{
				if args[0] != "pub" && args[0] != "sub" {
					fmt.Println(color.Red.Text("请选择操作类型 [pub|sub]"))
					return
				}
				switch args[0] {
					case "pub":
						if len(args) == 2 && args[1] != "" {
							client.WriteMessage(1, []byte(args[1]))
						}else{
							fmt.Println(color.Red.Text("请输入要发送的消息内容"))
							return
						}
					case "sub":
						for {
							_, data, err := client.ReadMessage()
							if err != nil {
								break
							}
							fmt.Println("[info][message]：", string(data))
						}
				}
			}
		},
	}
	return command
}
